package cn.alise.controller.admin;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import cn.alise.controller.common.BaseController;
import cn.alise.enums.EnumClass;
import cn.alise.qdp.model.common.OrganTree;
import cn.alise.qdp.model.organ.Organ;
import cn.alise.qdp.model.user.User;
import cn.alise.qdp.service.admin.OrganService;
import cn.alise.qdp.service.user.UserService;
import cn.alise.util.JSONResult;

import com.alibaba.fastjson.JSONArray;

/**
 * 单位管理控制器
 */
@Controller
@RequestMapping(value = "/organ")
public class OrganController extends BaseController {

	private static final long serialVersionUID = 3071751434812887748L;
	private static final String ERROR_TITLE = "_error";
	private static final String REDIRECT_LIST = "redirect:list";

	@Resource(name = "organService")
	private OrganService organService;
	
	@Resource(name = "userService")
	private UserService userService;
	
	/**
	 * 单位列表
	 */
	@RequestMapping(value = "/list")
	public String list(HttpServletRequest request, Model model,
			Organ organ) {
		//session 获取organId
		String organId = this.getAccountFromSession().getOrganId();
		
		// 获取所有单位
		Organ args = new Organ();
		args.setOrganId(Long.parseLong(organId));
		if (!StringUtils.isEmpty(organ.getOrganName())) {
			args.setOrganName(organ.getOrganName());
			List<Organ> organList = this.organService.listTree(args);
			model.addAttribute("list", organList);
			if (!CollectionUtils.isEmpty(organList)) {
				model.addAttribute("parentId", organList.get(0).getParentId());
			}
		} else {
			List<Organ> organList = this.organService.listTree(args);
			List<Organ> organNew = new ArrayList<Organ>();
			if (organList.size() > 0) {
				organNew.add(organList.get(0));
				int margin = 20;
				List<Organ> clist = createTableChildren(organList, organList.get(0).getOrganId().toString(), margin);
				for (int x=0; x<clist.size(); x++) {
					organNew.add(clist.get(x));
				}
			}
			
			model.addAttribute("list", organNew);
			model.addAttribute("parentId", organList.get(0).getParentId());
		}

		return "pages/organ/organ-list";
	}
	
	/**
	 * 跳转到单位创建页面
	 */
	@RequestMapping(value = "/create", method = RequestMethod.GET)
	public String create(HttpServletRequest request, Model model) {
		
		return "pages/organ/organ-new";
	}
	
	/**
	 * 获取所有一、二、三级单位
	 */
	@RequestMapping(value = "/findAllTrees")
	@ResponseBody
	public List<OrganTree> findAllTrees() {
		//session 获取organId
		String organId = this.getAccountFromSession().getOrganId();
		
		// 获取所有单位
		Organ args = new Organ();
		args.setOrganId(Long.parseLong(organId));
		List<Organ> organList = this.organService.listTree(args);
		List<OrganTree> organTree = new ArrayList<OrganTree>();
		if (organList.size() > 0) {
			OrganTree tree = new OrganTree();
			tree.setId(organList.get(0).getOrganId());
			tree.setText(organList.get(0).getOrganName());
			tree.setPid("");
			List<OrganTree> clist = createComboTreeChildren(organList, organList.get(0).getOrganId().toString());
			tree.setChildren(clist);
			organTree.add(tree);
		}
		
		return organTree;
	}
	
	/**
	 * ajax单位同中文名检测
	 */
	@RequestMapping(value = "/sameCheckOrganName", method = RequestMethod.POST)
	public void sameCheckOrganName(HttpServletRequest request, HttpServletResponse response) {
		
		Organ args = new Organ();
		String organName = request.getParameter("organName");
		args.setOrganName(organName);
		
		//ajax检测同名单位组织名称
		if(organName!=null && !"".equals(organName)) {
			JSONResult result = new JSONResult();
			List<Organ> check = this.organService.list(args);
			
			if(check.size()>0) {
				result.setStatus(1);
				result.setMessage("1");
				this.getPrintWriter(response, new JSONResult(1,new Object(),"已有相同的组织单位名称!"));
			} else {
				result.setStatus(0);
				result.setMessage("0");
				this.getPrintWriter(response, new JSONResult(0,new Object(),"没有相同名称!"));
			}
		}
	}
	
	/**
	 * 新增单位
	 */
	@RequestMapping(value = "/insert", method = RequestMethod.POST)
	public String insert(HttpServletRequest request, Organ organ, RedirectAttributes attr) {
		
		//session 获取userId
		Long userId = this.getAccountFromSession().getUserId();
		
		organ.setParentId(organ.getParentId());//上级单位Id
		
		organ.setCreater(userId);
		organ.setCreatedTime(new Timestamp(new Date().getTime()));
		
		organ.setStatus(1);
		// 调用接口执行更新
		int row = this.organService.save(organ);
		
		// 根据上级机构ID获取上级机构信息
		Organ parentOrgan = new Organ();
		parentOrgan.setOrganId(organ.getParentId());
		parentOrgan = this.organService.get(parentOrgan);
		
		organ.setParentIdStr(parentOrgan.getParentIdStr() + "," + organ.getOrganId());
		// 修改该机构的parentIdStr字段
		this.organService.update(organ);
		
		if (row >= 0) {
			attr.addFlashAttribute(ERROR_TITLE, "单位新增成功！");
		} else {
			attr.addFlashAttribute(ERROR_TITLE, "单位新增失败！");
		}
		return REDIRECT_LIST;
		
	}
	
	/**
	 * 跳转到单位编辑页面
	 */
	@RequestMapping(value = "/edit", method = RequestMethod.GET)
	public String edit(HttpServletRequest request, Model model, Organ organ) {
		
		Organ args = new Organ();
		args.setOrganId(organ.getOrganId());
		
		// 获取修改的单位信息
		organ = this.organService.get(args);
		model.addAttribute("organ", organ);
		
		// 获取上级单位信息
		organ = this.organService.getParent(args);
		model.addAttribute("organParent", organ);
		
		return "pages/organ/organ-edit";
	}
	
	/**
	 * 修改单位
	 */
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public String update(HttpServletRequest request, Model model, Organ organ, RedirectAttributes attr) {
		
		//session 获取userId
		Long userId = this.getAccountFromSession().getUserId();
		
		if(organ.getParentId()!=null && organ.getParentId()!=0) {
			organ.setParentId(organ.getParentId());//上级单位Id
		} else {
			organ.setParentId(null);//上级单位Id
		}
		
		// 调用接口执行更新
		organ.setCreater(userId);
		organ.setUpdatedTime(new Timestamp(new Date().getTime()));
		int row = this.organService.update(organ);
		
		if (row >= 0) {
			attr.addFlashAttribute(ERROR_TITLE, "单位修改成功！");
		} else {
			attr.addFlashAttribute(ERROR_TITLE, "单位修改失败！");
		}
		return REDIRECT_LIST;
	}
	
	/**
	 * 删除组织单位信息，删除组织单位信息需要检查是否存在人员
	 */
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public void delete(HttpServletRequest request, HttpServletResponse response){
		
		JSONResult result = new JSONResult();
		String organId = request.getParameter("organId");
		//拆分organId
		String[] organIdArr = organId.split(",");
		int row = 1;
		//循环删除
		for(int i=0; i<organIdArr.length; i++) {
			Organ organ = new Organ();
			organ.setOrganId(Long.parseLong(organIdArr[i]));
			List<Organ> organList = new ArrayList<Organ>();
			organList = this.organService.listTree(organ);
			if (organList != null && organList.size() > 0) {
				boolean results = true;
				String resultstr = "";
				for (Organ organ2:organList) {
					// 检查将要删除的组织单位下面是否还存在人员
					User user = new User();
					user.setOrganId(organ2.getOrganId().toString());
					List<User> list = this.userService.judgeUserByOrganId(user);
					if (!CollectionUtils.isEmpty(list)) {
						results=false;
						resultstr=organ2.getOrganName() + "下或其子单位下存在人员,不能删除！";
						break;
					}
				}
				
				if (results) {
					// 对单位进行逻辑删除(包含删除其下所有子单位)
					organ.setStatus(EnumClass.Status.UNVALID.getKey());
					row = this.organService.update(organ);
					// 修改user表的状态为注销
					User user = new User();
					user.setAccount(organ.getOrganId().toString());
					user.setStatus(EnumClass.UserStatus.CANCEL.getKey());
					this.userService.update(user);
				} else {
					result.setMessage(resultstr);
					getPrintWriter(response,JSONArray.toJSONString(result));
					return;
				}
				
			}
			
		}
		if (row != 0) {
			result.setMessage("删除成功！");
			getPrintWriter(response,JSONArray.toJSONString(result));
		} else {
			result.setMessage("删除失败");
			getPrintWriter(response,JSONArray.toJSONString(result));
		}
	}
	
	/**
	 * 查询单位详情
	 */
	@RequestMapping(value = "/query")
	public String query(HttpServletRequest request, Model model, Organ organ) {
		
		organ = this.organService.get(organ);
		
		model.addAttribute("organ", organ);
		
		return "pages/organ/organ-query";
	}
	
	/** 
	 * 递归设置单位树(table展示)
	 * @return 
	 */  
	private List<Organ> createTableChildren(List<Organ> list, String parentId, int margin) {  
		List<Organ> childList = new ArrayList<Organ>(); 
		margin = margin + 20;
	    for (int j = 0; j < list.size(); j++) {  
	        Organ tableChild = (Organ) list.get(j);
	        if (tableChild.getParentId() != null) {
	        	if (tableChild.getParentId().toString().equals(parentId)) {
        			tableChild.setLevel(margin);
		        	childList.add(tableChild);
		        	List<Organ> clist = createTableChildren(list, tableChild.getOrganId().toString(), margin);
		        	for (int x=0; x<clist.size(); x++) {
		        		childList.add(clist.get(x));
		        	}  
		        }  
	        }
	    }  
	    return childList;  
	} 
	
	/** 
	 * 递归设置单位树(tree展示)
	 * @return 
	 */  
	private List<OrganTree> createComboTreeChildren(List<Organ> list, String fid) {  
		List<OrganTree> childList = new ArrayList<OrganTree>();  
	    for (int j = 0; j < list.size(); j++) {  
	        Organ treeChild = (Organ) list.get(j); 
	        if (treeChild.getParentId() != null) {
	        	if (treeChild.getParentId().toString().equals(fid)) {
		            OrganTree tree = new OrganTree();
		            tree.setId(treeChild.getOrganId());
		            tree.setText(treeChild.getOrganName());
					if(treeChild.getParentId()!=null) {
						tree.setPid(treeChild.getParentId().toString());
					} else {
						tree.setPid("");
					}
					
					List<OrganTree> clist = createComboTreeChildren(list, treeChild.getOrganId().toString());
					tree.setChildren(clist);
					childList.add(tree);
		        } 
	        }
	         
	    }  
	    return childList;  
	} 
}